const Base = require('./base.js');
const rq = require('request-promise');

module.exports = class extends Base {
  __before() {
    super.__before();
    this.userService = think.rpc.user.user;
  }
  async saveUserAction() {
    const userId = this.getUserId();
    const avatarUrl = this.strVal('avatarUrl');
    const city = this.strVal('city');
    const country = this.strVal('country');
    const gender = this.strVal('gender');
    const nickName = this.strVal('nickName');
    const language = this.strVal('language');
    const province = this.strVal('province');
    const userInfo = {
      avatar: avatarUrl,
      city,
      country,
      sex: parseInt(gender) || 0,
      nickname: nickName,
      language,
      province
    };
    think.logger.info('update user info ', userInfo);
    await this.userService.updateUserInfoById(userId, userInfo);
    return this.success();
  }
  async loginAction() {
    const code = this.strVal('code');
    if (!code) {
      return this.fail('code can not be empty');
    }
    const session = await this.code2Session(code);
    const userId = await this.userService.findOrCreateByOpenId(session.openid);
    const userInfo = {
      id: userId,
      sessionKey: session.session_key,
      openid: session.openid
    };
    const token = think.userUtil.setUser(userInfo);
    return this.success(token);
  }
  async code2Session(code) {
    const pro = think.config('minipro');
    const url = `https://api.weixin.qq.com/sns/jscode2session?appid=${pro.appId}&secret=${pro.appSecret}&js_code=${code}&grant_type=authorization_code`;
    let rt;
    try {
      rt = JSON.parse(await rq.get(url));
    } catch (e) {
      think.logger.error('code2Session exception:', e);
      think.throw('code 授权失败');
    }
    if (!rt.errcode) {
      return rt;
    }
    think.logger.error('code2Session error:', rt);
    think.throw(rt.errMsg);
  }
};
